package kotan.view.common;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class FileField extends JPanel {

    private static final long serialVersionUID = 1L;
    private JTextField textField;
    private JFileChooser chooser;

    public FileField() {
        this(16, JFileChooser.FILES_ONLY);
    }
    
    public FileField(int size, int fileSelectionMode) {
        textField = new JTextField(size);
        JButton button = new JButton("...");
        button.setMargin(new Insets(0, 0, 0, 0));
        button.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                openDialog();
            }
        });
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = GridBagConstraints.RELATIVE;
        gbc.weightx = 1f;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        add(textField, gbc);
        gbc.weightx = 0f;
        gbc.fill = GridBagConstraints.NONE;
        add(button, gbc);
        chooser = new JFileChooser(textField.getText());
        chooser.setFileSelectionMode(fileSelectionMode);
    }

    protected void openDialog() {
        int result = chooser.showOpenDialog(this);
        if (result != JFileChooser.APPROVE_OPTION) return;
        this.textField.setText(chooser.getSelectedFile().getAbsolutePath());
    }
    
    public String getText() {
        return this.textField.getText();
    }
    
    public void setText(String text) {
        this.textField.setText(text);
    }

}
